package com.ruibang.glass.produce.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64OutputStream;

import java.io.*;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {
    public static final int ZIP_BUFFER_SIZE = 8192;
    public static final String XML_ENCODING = "UTF-8";

    public static String decodeBase64ZippedString(String loggingString64) throws IOException {
        if (loggingString64 == null || loggingString64.isEmpty()) {
            return "";
        }
        StringWriter writer = new StringWriter();
        byte[] bytes64 = Base64.decodeBase64(loggingString64.getBytes());
        ByteArrayInputStream zip = new ByteArrayInputStream(bytes64);
        try (GZIPInputStream unzip = new GZIPInputStream(zip, ZIP_BUFFER_SIZE); BufferedInputStream in = new BufferedInputStream(unzip, ZIP_BUFFER_SIZE); InputStreamReader reader = new InputStreamReader(in, XML_ENCODING)) {

            char[] buff = new char[ZIP_BUFFER_SIZE];
            for (int length; (length = reader.read(buff)) > 0; ) {
                writer.write(buff, 0, length);
            }
        }
        return writer.toString();
    }

    public static String encodeBase64ZippedString(String in) throws IOException {
        Charset charset = Charset.forName(XML_ENCODING);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        try (Base64OutputStream base64OutputStream = new Base64OutputStream(baos); GZIPOutputStream gzos = new GZIPOutputStream(base64OutputStream)) {
            gzos.write(in.getBytes(charset));
        }
        return baos.toString();
    }

}